package services

import (
	"awesome-devops/applications/backend/modules/define"
	"awesome-devops/applications/models"
	"awesome-devops/boot"
	"errors"
	"fmt"
	"gitee.com/jjawesomejj/awesome-util/echo"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"gitee.com/jjawesomejj/awesome-util/helper/timeHelper"
	"strconv"
	"time"
)

//token 最大过期时间
const MAX_TTL = 60 * 60 * 24 * 7

type UserService struct {
}

func (userService *UserService) Login(email string, password string) models.UserToken {
	userObj := models.User{}
	res := boot.GetDbConnection().Table(userObj.TableName()).
		Where("email", email).
		Where("password", password).
		Where("delete_time=0").First(&userObj)
	if res.Error != nil {
		panic(define.NewRequestError("账号或者密码错误", 10001))
	}
	if userObj.Id == 0 {
		panic(define.NewRequestError("账号或者密码错误", 10001))
	}
	userAccessToken := models.UserToken{}
	userAccessToken.Uid = userObj.Id
	userAccessToken.AccessToken = commonhelper.Md5(strconv.Itoa(int(userObj.Id)) + commonhelper.Rand(10) + strconv.FormatInt(timeHelper.NowInt(), 10))
	userAccessToken.ExpiredAt = int(timeHelper.NowInt() + MAX_TTL)
	userAccessToken.CreateTime = time.Now()
	userAccessToken.UpdateTime = time.Now()
	res = boot.GetDbConnection().Save(&userAccessToken)
	if res.Error != nil {
		fmt.Println(res.Error, "err")
		panic(define.NewRequestError(res.Error.Error(), 10001))
	}
	return userAccessToken
}

func (userService *UserService) InitAdminUser(email string, password string) string {
	userObj := models.User{}
	user := models.User{}
	res := boot.GetDbConnection().Table(userObj.TableName()).Table(user.TableName()).Delete(&models.User{}, []int{1})
	if res.Error != nil {
		panic(define.NewRequestError(res.Error.Error(), 10001))
	}
	user.Id = 1
	user.Username = email
	user.Email = email
	now := time.Now().Local()
	user.Password = commonhelper.Md5(password)
	user.CreateTime = now
	user.UpdateTime = now
	res = boot.GetDbConnection().Save(&user)
	if res.Error != nil {
		panic(define.NewRequestError(res.Error.Error(), 10001))
	}
	echo.Green(commonhelper.Format("admin user init success email[{}] password[{}]", email, password))
	return userObj.AccessToken
}

func (userService *UserService) GetUserByAccessToken(token string) (models.User, error) {
	userToken := models.UserToken{}
	user := models.User{}
	res := boot.GetDbConnection().Table(userToken.TableName()).Where("access_token", token).
		Where("delete_time=0").First(&userToken)
	if res.Error != nil {
		return user, errors.New("无效token")
	}
	if userToken.ExpiredAt <= int(timeHelper.NowInt()) {
		return user, errors.New("无效token")
	}
	res = boot.GetDbConnection().Table(user.TableName()).Where("id", userToken.Uid).
		Where("delete_time=0").First(&user)
	if res.Error != nil {
		return user, errors.New("无效token")
	}
	return user, nil
}
